package com.home.zzm.datastore

import android.os.Bundle
import android.util.Log
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.PreferenceDataStoreFactory
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.emptyPreferences
import androidx.datastore.preferences.core.preferencesKey
import androidx.datastore.preferences.createDataStore
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import java.io.File
import java.io.IOException

class MainActivity : AppCompatActivity() {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    val ds: DataStore<Preferences> = this.createDataStore("name")
    val btn1 = findViewById<Button>(R.id.button)
    val btn2 = findViewById<Button>(R.id.button2)
    btn1.setOnClickListener {
      val NAME = preferencesKey<String>("username")
      CoroutineScope(Dispatchers.IO).launch {
        ds?.edit { it[NAME] = "zzm" }
      }
    }
    btn2.setOnClickListener{
      val NAME = preferencesKey<String>("username")
      CoroutineScope(Dispatchers.IO).launch {
        val getName = ds.data.map { it[NAME] }
        Log.e("zzm debug", "getName : $getName")
      }
    }
  }
}